package com.mixcus.server.controller;

import com.mixcus.server.dto.UserDto;
import com.mixcus.server.entity.Result;
import com.mixcus.server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Result login(@RequestBody UserDto userDto) {

        String userName = userDto.getUserName();

        String password = userDto.getUserPassword();

        if(userName.equals("")){
            return new Result(false, "用户名不能为空");
        }
        if(password.equals("")){
            return new Result(false, "密码不能为空");
        }

        if(userService.hasUserName(userName) == 0){
            return new Result(false, "用户名不存在");
        }

        if(!userService.getPassword(userName).equals(password)){
            return new Result(false, "账号或密码错误");
        }

        if(userService.getUserRole(userName)!=(userDto.getUserRole())){
            return new Result(false,"角色信息错误");
        }
        //返回用户信息

        return new Result(true,"登入成功",userService.getUserResult(userDto));
    }

    @PostMapping("/register")
    public Result register(@RequestBody UserDto userDto) {

        String userName = userDto.getUserName();

        String password = userDto.getUserPassword();

        if(userName.equals("")){
            return new Result(false, "用户名不能为空");
        }
        if(password.equals("")){
            return new Result(false, "密码不能为空");
        }

        if(userService.hasUserName(userName)!=0) {
            return new Result(false, "用户名已存在");
        }
        //密码校验

        //添加用户信息
        try {
            userService.addUser(userDto);
            return new Result(true,"注册成功");
        }catch (Exception e){
            //调用自定义异常处理
            return new Result(false, "注册失败");
        }
    }
}

